//
//  DR_FileMoreActionSheet.swift
//  DocReaderRP
//
//  Created by  mac on 2025/11/10.
//

import UIKit
import SnapKit

struct DR_FileMoreAction {
    let title: String
    let iconName: String
    let action: () -> Void
    let shouldAutoHide: Bool // 是否自动隐藏 actionSheet，默认为 true
    
    init(title: String, iconName: String, shouldAutoHide: Bool = true, action: @escaping () -> Void) {
        self.title = title
        self.iconName = iconName
        self.shouldAutoHide = shouldAutoHide
        self.action = action
    }
}

class DR_FileMoreActionSheet: UIView {
    
    var onDismiss: (() -> Void)?
    
    private let backgroundView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        return view
    }()
    
    private let containerView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    private let fileInfoView: UIView = {
        let view = UIView()
        view.backgroundColor = .clear
        return view
    }()
    
    private let fileIconView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "folder_icon")
        imageView.contentMode = .scaleAspectFill
        return imageView
    }()
    
    private let fileNameLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 15, weight: .medium)
        label.textColor = .black
        return label
    }()
    
    private let fileMetadataLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 13)
        label.textColor = "#ADADAD".toColor
        return label
    }()
    
    private let closeButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "more_close"), for: .normal)
        return button
    }()
    
    private let buttonsStackView: UIStackView = {
        let stackView = UIStackView()
        stackView.axis = .vertical
        stackView.distribution = .fillEqually
        stackView.spacing = 12
        return stackView
    }()
    
    private var actionButtons: [UIButton] = []
    private var actions: [DR_FileMoreAction] = []
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        setupConstraints()
        setupActions()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        addSubview(backgroundView)
        addSubview(containerView)
        
        containerView.addSubview(fileInfoView)
        fileInfoView.addSubview(fileIconView)
        fileInfoView.addSubview(fileNameLabel)
        fileInfoView.addSubview(fileMetadataLabel)
        fileInfoView.addSubview(closeButton)
        
        containerView.addSubview(buttonsStackView)
    }
    
    private func setupConstraints() {
        backgroundView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        containerView.snp.makeConstraints { make in
            make.leading.trailing.bottom.equalToSuperview()
            make.height.equalTo(335)
        }
        
        fileInfoView.snp.makeConstraints { make in
            make.leading.trailing.top.equalToSuperview()
            make.height.equalTo(91)
        }
        
        fileIconView.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(15)
            make.top.equalToSuperview().offset(16)
            make.width.height.equalTo(60)
        }
        
        fileNameLabel.snp.makeConstraints { make in
            make.leading.equalTo(fileIconView.snp.trailing).offset(12)
            make.trailing.lessThanOrEqualTo(closeButton.snp.leading).offset(-12)
            make.top.equalToSuperview().offset(25)
        }
        
        fileMetadataLabel.snp.makeConstraints { make in
            make.leading.equalTo(fileNameLabel)
            make.trailing.lessThanOrEqualTo(closeButton.snp.leading).offset(-12)
            make.top.equalTo(fileNameLabel.snp.bottom).offset(8)
        }
        
        closeButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-15)
            make.top.equalToSuperview().offset(16)
            make.width.height.equalTo(24)
        }
        
        buttonsStackView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(15)
            make.top.equalTo(fileInfoView.snp.bottom).offset(30)
            make.height.equalTo(175)
        }
    }
    
    private func setupActions() {
        backgroundView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismiss)))
        closeButton.addTarget(self, action: #selector(dismiss), for: .touchUpInside)
    }
    
    @objc private func dismiss() {
        hide()
    }
    
    func configure(with fileModel: DR_SearchFileModel, actions: [DR_FileMoreAction]) {
        self.actions = actions
        
        fileNameLabel.text = fileModel.fileName
        fileMetadataLabel.text = "\(fileModel.date) \(fileModel.size)"
        fileIconView.image = UIImage(named: "folder_icon")
//        // 根据文件类型设置图标
//        switch fileModel.fileType {
//        case "PDF":
//            fileIconView.image = UIImage(named: "home_pdf")
//        case "Word":
//            fileIconView.image = UIImage(named: "home_word")
//        case "Excel":
//            fileIconView.image = UIImage(named: "home_excel")
//        default:
//            fileIconView.image = UIImage(named: "folder_icon")
//        }
        
        // 清除旧的按钮
        buttonsStackView.arrangedSubviews.forEach { $0.removeFromSuperview() }
        actionButtons.forEach { $0.removeFromSuperview() }
        actionButtons.removeAll()
        
        // 创建按钮行（每行4个）
        let rows = stride(from: 0, to: actions.count, by: 4).map { startIndex in
            let endIndex = min(startIndex + 4, actions.count)
            return Array(actions[startIndex..<endIndex])
        }
        
        // 为每行创建水平 StackView
        var buttonIndex = 0
        rows.forEach { rowActions in
            let rowStackView = UIStackView()
            rowStackView.axis = .horizontal
            rowStackView.distribution = .fillEqually
            rowStackView.spacing = 9
            
            rowActions.forEach { action in
                let button = createActionButton(action: action, index: buttonIndex)
                rowStackView.addArrangedSubview(button)
                actionButtons.append(button)
                buttonIndex += 1
            }
            
            // 如果不足4个按钮，添加占位视图
            let remainingCount = 4 - rowActions.count
            for _ in 0..<remainingCount {
                let placeholderView = UIView()
                rowStackView.addArrangedSubview(placeholderView)
            }
            
            buttonsStackView.addArrangedSubview(rowStackView)
        }
    }
    
    private func createActionButton(action: DR_FileMoreAction, index: Int) -> UIButton {
        let button = UIButton(type: .custom)
        button.backgroundColor = "#F6F7FF".toColor
        button.layer.cornerRadius = 12
        button.isUserInteractionEnabled = true // 确保按钮可以接收触摸事件
        
        // 创建垂直布局
        let stackView = UIStackView()
        stackView.axis = .vertical
        stackView.alignment = .center
        stackView.spacing = 8
        stackView.isUserInteractionEnabled = false // 禁用 stackView 的交互，让按钮接收事件
        
        // 图标
        let iconView = UIImageView()
        iconView.image = UIImage(named: action.iconName) ?? UIImage(systemName: "doc")
        iconView.contentMode = .scaleAspectFit
        iconView.isUserInteractionEnabled = false
        iconView.snp.makeConstraints { make in
            make.width.height.equalTo(24)
        }
        
        // 文字
        let label = UILabel()
        label.text = action.title
        label.font = UIFont.systemFont(ofSize: 13)
        label.textColor = .black
        label.textAlignment = .center
        label.isUserInteractionEnabled = false
        
        stackView.addArrangedSubview(iconView)
        stackView.addArrangedSubview(label)
        
        button.addSubview(stackView)
        stackView.snp.makeConstraints { make in
//            make.edges.equalToSuperview()
            make.top.bottom.equalToSuperview().inset(10)
            make.leading.trailing.equalToSuperview().inset(5)
//            make.edges.equalToSuperview().inset(12)
        }
        
        button.addTarget(self, action: #selector(actionButtonTapped(_:)), for: .touchUpInside)
        button.tag = index
        
        return button
    }
    
    @objc private func actionButtonTapped(_ sender: UIButton) {
        let index = sender.tag
        if index < actions.count {
            let action = actions[index]
            action.action()
            // 只有 shouldAutoHide 为 true 时才自动隐藏
            if action.shouldAutoHide {
                hide()
            }
        }
    }
    
    func show(in parentView: UIView) {
        parentView.addSubview(self)
        parentView.bringSubviewToFront(self)
        
        self.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            self.topAnchor.constraint(equalTo: parentView.topAnchor),
            self.leadingAnchor.constraint(equalTo: parentView.leadingAnchor),
            self.trailingAnchor.constraint(equalTo: parentView.trailingAnchor),
            self.bottomAnchor.constraint(equalTo: parentView.bottomAnchor)
        ])
        
        // 初始状态：背景透明，容器在底部外
        backgroundView.alpha = 0
        containerView.transform = CGAffineTransform(translationX: 0, y: 335)
        
        // 强制布局
        layoutIfNeeded()
        
        // 再次确保在最上层
        parentView.bringSubviewToFront(self)
        
        // 动画显示
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut) {
            self.backgroundView.alpha = 1
            self.containerView.transform = .identity
        } completion: { _ in
            parentView.bringSubviewToFront(self)
        }
    }
    
    func hide() {
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn) {
            self.backgroundView.alpha = 0
            self.containerView.transform = CGAffineTransform(translationX: 0, y: 335)
        } completion: { _ in
            self.removeFromSuperview()
            self.onDismiss?()
        }
    }
}


